package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired
    private HttpSession session;
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Override
    public Boolean add(Orders orders) {
        Long user = (Long) session.getAttribute("user");
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findAll(user);
        BigDecimal amountTotal = new BigDecimal("0");//用户购物车总金额
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal amount = shoppingCart.getAmount();
            amountTotal=amountTotal.add(amount);
        }
        orders.setAmount(amountTotal);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        Integer add = orderMapper.add(orders);
        return add>0;
    }

    @Override
    public Page<Orders> findByPage(Long userId, Integer page, Integer pageSize) {
        Long user = (Long) session.getAttribute("user");
        PageHelper.startPage(page, pageSize);
        List<Orders> byPage = orderMapper.findByPage(user);
        PageInfo pageInfo = new PageInfo(byPage);

        Page<Orders> page1 = new Page<>();
        page1.setTotal(pageInfo.getTotal());
        page1.setRecords(pageInfo.getList());

        return page1;
    }

    @Override
    public Orders again(Long id) {
        Orders again = orderMapper.again(id);
        return again;
    }
}
